#!/usr/bin/perl
#vol_delete.cgi

require './diskman-lib.pl';

&ReadParse();
#open(GG, ">>/root/vd");
my ($err_msg, $log_ev, $log_msg, $log_pri);

$err_msg="";
$log_ev="";

my $volname = $in{'volname'};
if (!$volname) {
	$err_msg = $text{"err_cgiparam"};
	goto ERROR_OUT;
}

my $mkfs_lock;
$mkfs_lock = check_lock();
if ($mkfs_lock) {
	$err_msg = $text{"err_mkfslocked"};
	goto ERROR_OUT;
}
	
my (@rdinfo, $r, $rr);

@rdinfo = get_check_raid_info();
$found = 0;
foreach $r (@rdinfo) {
	if ($r->{'volname'} eq $volname) {
		$rr = $r;
		$found = 1;
		last;
	}
}

if (!$found) {
	#finish latter
	$err_msg = $text{"err_configchanged"};
	goto ERROR_OUT;
}

my ($out, $mddev, @rdev);
$mddev = $rr->{'device'};
my ($d, $p);


#check whether the status of volume
if ($rr->{'status'} eq 'new') {
	#raid stop
	$out = `/sbin/mdadm -S $mddev 2>&1`;
	if ($?) {
		$err_msg = $text{"err_volbusy"};
		goto ERROR_OUT;
	}
	#reset the partition to 'fa'

	foreach $rdev (@{$rr->{'rdevs'}}) {
		#$rdev =~ /(\S+)(\d+)/;
		#$d = $1;
		#$p = $2;
		$out = `/usr/local/sbin/mkfs.xfs $rdev -f 2>&1`;
	}
        del_raidtab($mddev);
        del_fstab($mddev);
	delete_voltab($volname);
}
elsif ($rr->{'status'} eq 'normal') {
	#1`elete the information of the disk
	$out = `/sbin/lvm pvremove $mddev -ff`;
	if ($?) {
		#$err_msg = "Can not remove PV $mddev!";
		$err_msg = $text{'err_pvinvg'};
		goto ERROR_OUT;
	}
	#$out = `dd if=/dev/zero of=$mddev bs=1024 count=1024 2>&1`;
	#raid stop
	$out = `/sbin/mdadm -S $mddev 2>&1`;
	#reset the partition to 'fa'
	foreach $rdev (@{$rr->{'rdevs'}}) {
		$out = `/usr/local/sbin/mkfs.xfs $rdev -f 2>&1`;
	}
	#goto ERROR_OUT;
        del_raidtab($mddev);
        #del_fstab($mddev);
	#delete_voltab($volname);
}
else {
	$err_msg = $text{"err_configchanged"};
	goto ERROR_OUT;	
}
#close(GG);
$log_ev = $text{'log_ev_delvolume_ok'};
$log_msg= &text('log_msg_delvolume_ok', $volname);
nas_syslog($text{'my_log_minor'}, 'naslog_info', $log_ev, $log_msg);
redirect("index.cgi");

ERROR_OUT:
#close(GG);
&error_setup($text{'del_err_title'});
&error($err_msg);
